package br.com.loja;

import br.com.loja.framework.hibernate.HibernateUtil;
import br.com.loja.util.DBCreator;
import br.com.loja.util.PropertiesApp;
import br.com.loja.util.i18n.Language;
import br.com.loja.view.swing.MainDesktopFrame;
import com.jgoodies.looks.plastic.Plastic3DLookAndFeel;
import com.jgoodies.looks.plastic.theme.SkyRed;
import java.awt.Rectangle;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.hibernate.HibernateException;
import org.hibernate.Session;

/**
 *
 * @author David Luiz
 */
public class LojaApp extends JFrame {

    private static final long serialVersionUID = 1L;

    private static final int TIME_WAIT = 1250;

    private JLabel lblImg;
    private JLabel lblStatus;
    private JProgressBar bar;

    public LojaApp() {

        initComponents();

    }

    private void initComponents() {

        lblImg = new JLabel();
        lblStatus = new JLabel();
        bar = new JProgressBar();

        Rectangle r = this.getGraphicsConfiguration().getBounds();

        Double height = r.getHeight();
        Double width = r.getWidth();

        this.setBounds((width.intValue() - 480) / 2, (height.intValue() - 330) / 2, 480, 330);

        setUndecorated(true);

        lblImg.setIcon(new ImageIcon(getClass().getResource("/resource/img/spl_screen_loja.png"))); // NOI18N
        lblImg.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        lblImg.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        lblImg.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        bar.setStringPainted(true);
        lblStatus.setText("Iniciando...");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                        .addComponent(lblImg)
                        .addGap(0, 0, Short.MAX_VALUE))
                .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(bar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(lblStatus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap())
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                        .addComponent(lblImg)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lblStatus)
                        .addContainerGap())
        );

        pack();
    }

    public void setStatus(String status, int bar) {

        this.lblStatus.setText(status);
        this.bar.setValue(bar);

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        new Thread() {

            @Override
            public void run() {

                LojaApp lojaApp = new LojaApp();

                try {

                    sleep(TIME_WAIT);

                    PropertiesApp properties = PropertiesApp.getInstance();

                    int progress = 2;

                    lojaApp.setVisible(true);

                    lojaApp.setStatus("Carregando propriedades de idioma...", progress += 14);

                    sleep(TIME_WAIT);

                    Language language = Language.getInstance();

                    lojaApp.setStatus("Carregando Look&Feel...", progress += 14);

                    sleep(TIME_WAIT);

                    try {

                        Plastic3DLookAndFeel.setPlasticTheme(new SkyRed());
                        UIManager.setLookAndFeel(new Plastic3DLookAndFeel());

                    } catch (UnsupportedLookAndFeelException e) {
                        System.err.println("Não foi possivel carregar LookAndFeel.");
                        e.printStackTrace();
                    }

                    lojaApp.setStatus("Carregando propriedades de acesso ao banco...", progress += 14);

                    sleep(TIME_WAIT);

                    String url = properties.getPropertyValue("jdbc.url");
                    String user = properties.getPropertyValue("jdbc.user");
                    String pwd = properties.getPropertyValue("jdbc.password");

                    lojaApp.setStatus("Verificando conexão com banco de dados...", progress += 14);

                    sleep(TIME_WAIT);

                    if (DBCreator.createDB(url, user, pwd)) {

                        try {

                            lojaApp.setStatus("Testando banco de dados...", progress += 14);

                            sleep(TIME_WAIT);

                            Session session = HibernateUtil.getSession();
                            session.close();

                            lojaApp.setStatus("Carregando tela inicial...", progress += 14);

                            sleep(TIME_WAIT);

                            JFrame mainDesktopFrame = new MainDesktopFrame();
                            System.out.println(language.getString("db.test.ok"));
                            System.out.println(language.getString("welcome"));

                            lojaApp.setStatus("Concluido.", progress += 14);

                            sleep(TIME_WAIT);

                            mainDesktopFrame.setVisible(true);

                        } catch (InterruptedException | HibernateException e) {
                            //implementar log
                            JOptionPane.showMessageDialog(null, "Falha ao iniciar: " + e.getMessage(), "LojaApp", JOptionPane.ERROR_MESSAGE);
                        }
                    } else {
                        JOptionPane.showMessageDialog(null, language.getString("db.test.fail"), "LojaApp", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (InterruptedException e) {

                    JOptionPane.showMessageDialog(null, "Falha ao iniciar: " + e.getMessage(), "LojaApp", JOptionPane.ERROR_MESSAGE);

                }

                lojaApp.dispose();

            }

        }.start();
    }

}
